package com.kolon.framework.interceptor;

import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.kolon.framework.constant.Constant;
import com.kolon.framework.util.ComUtil;
import com.kolon.framework.util.MsgUtil;


/**
 * AD인증 체크 인터셉터
 * @author stone
 *
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
	
	/**
	 * 컨트롤러 실행 전 호출되는 인터셉터 함수
	 */
	@SuppressWarnings("rawtypes")
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler) throws Exception {
		HttpSession httpSession = request.getSession();
		String authUrl = MsgUtil.getMessage("auth.url");
		String weblgoinUrl = MsgUtil.getMessage("weblgoin.url");
		boolean check = true;
		// 세션 체크
		if (httpSession != null && httpSession.getAttribute(Constant.SESSION_USER_INFO) != null) {
			Map userMap = (Map)httpSession.getAttribute(Constant.SESSION_USER_INFO);
			// AD 인증 체크
			int responseCode = ComUtil.getResponseCode(authUrl, 
					(String)userMap.get("userId"), (String)userMap.get("userPw"));
			if (responseCode != 200)
				check = false;
		} else {
			check = false;
		}
		// AD 인증 및 세션이 없을 시
		if (!check) {
			httpSession.invalidate();
			// REFERER 생성
			String param = "";
			String referrer = "";
			referrer = request.getRequestURI();
			if (request.getQueryString() != null)
				referrer += "?"+request.getQueryString();
			param += "&qry=" + URLEncoder.encode(referrer, "UTF-8");
			weblgoinUrl += "?" + param;
			response.sendRedirect(request.getContextPath() + weblgoinUrl);
			return false;
		}
		return true;
	}

}
